import { MongoClient } from "mongodb";

const url = "mongodb://127.0.0.1:27017/";
const client = new MongoClient(url);

const records = [
  {
    name: "Westbrook",
    age: 32,
  },
  {
    name: "Howard",
    age: 35,
  },
];

async function run() {
  try {
    await client.connect();
    const db = client.db("hello");
    const res = await db.command({ ping: 1 }); // 测试数据库是否成功
    console.log("connected", res);
    // 数据的插入
    const userCollection = db.collection("user");
    // const result = await userCollection.insertOne({ name: "AD", age: 28 });
    // console.log(result);
    // const result = await userCollection.insertMany(records);
    // console.log(result);

    // 查找
    const result = await userCollection.findOne({ name: "AD" });
    console.log(result);
    /* const cursor = userCollection.find();
    // 使用forEach
    await cursor.forEach((doc) => console.log(doc)); */
    // 使用toArray()
    const results = await userCollection.find().toArray();
    console.log(results);
  } catch (error) {
    console.error("error", error);
  } finally {
    await client.close();
  }
}

run();
